import os
from flask import Blueprint, request, jsonify
from bson import ObjectId
from pymongo import MongoClient

rankings_bp = Blueprint('rankings', __name__)

# MongoDB 连接配置
MONGO_URI = os.getenv('MONGO_URI', 'mongodb://localhost:27017/')
DB_NAME = 'test'
# 创建MongoDB客户端
client = MongoClient(MONGO_URI)
db = client[DB_NAME]

def convert_objectid_to_str(data):
    """递归转换 ObjectId 为字符串"""
    if data is None:
        return None
    if isinstance(data, dict):
        return {key: convert_objectid_to_str(value) for key, value in data.items()}
    elif isinstance(data, list):
        return [convert_objectid_to_str(item) for item in data]
    elif isinstance(data, ObjectId):
        return str(data)
    return data


@rankings_bp.route('/rankings', methods=['GET'])
def get_rankings():
    """
    获取排行榜数据（直接从MongoDB查询）
    参数:
    - type: 排行榜类型 (hot/new/recommend/collect)
    """
    try:
        # 获取查询参数
        rank_type = request.args.get('type', 'hot')

        # 验证排行榜类型是否有效
        valid_types = ['hot', 'rising', 'comprehensive', 'collect']
        if rank_type not in valid_types:
            return jsonify({
                "code": 400,
                "message": f"Invalid ranking type. Valid types are: {', '.join(valid_types)}"
            }), 400

        # 查询数据库，获取指定排行榜类型的数据
        # 假设每个排行榜类型是单独存储的文档
        doc = db['rankings'].find_one({"rank_type": rank_type})

        if not doc:
            return jsonify({
                "code": 404,
                "message": f"No data found for ranking type: {rank_type}"
            }), 404

        # 获取排行榜数据
        ranking_data = doc.get("books", [])

        # 转换 ObjectId 为字符串
        ranking_data = convert_objectid_to_str(ranking_data)

        # 构建响应数据
        response_data = {
            "type": rank_type,
            "total": len(ranking_data),
            "list": ranking_data
        }

        return jsonify({
            "code": 200,
            "message": "success",
            "data": response_data
        })

    except Exception as e:
        return jsonify({
            "code": 500,
            "message": f"Server error: {str(e)}"
        }), 500
